<?php
/**
 * CopyTask.php class file.
 * @author wudg <544038230@qq.com>
 * @date 2020/11/5- 10:41 上午
 */

namespace console\components\tasks;


use common\components\misc\ImportLogger;
use console\components\helpers\ConsoleHelper;
use yii\di\Instance;
use yii\helpers\FileHelper;
use yii\queue\serializers\SerializerInterface;
use yii\redis\Connection;
use Yii;
class CopyTask extends BaseQueue
{

    /**
     * 队列名称
     * @var string
     */
    public $channel = 'queueCopyTb';

    public $logger;

    /**
     * 执行上货
     * @param array $args
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\base\Exception
     */
    public function run()
    {
        $this->logger = new ImportLogger($this->_createFilePath());
        $this->redis = Instance::ensure($this->redis, Connection::class);

        $this->serializer = Instance::ensure($this->serializer, SerializerInterface::class);

        if (($payload = $this->reserve(0)) !== null) {
            list($id, $message, $ttr, $attempt) = $payload;
            $this->delete($id);
            if ($this->handleMessage($id, $message, $ttr, $attempt)) {
                $this->logger->add('上货任务['.$id.']执行完成');
                Yii::$app->db->close();
            }
        }
    }

    /**
     * 目录初始化
     * @return bool|string
     * @throws \yii\base\Exception
     */
    protected function _createFilePath()
    {
        $path = Yii::getAlias('@runtime/task/copy_tb/');

        //目录如果不存就先创建目录
        if(!is_dir($path)) {
            FileHelper::createDirectory($path);
        }

        return $path;
    }


}
